package com.itxh.core.builder;

import com.itxh.core.config.Configuration;
import com.itxh.core.io.Resources;
import com.itxh.core.utils.DocumentUtils;
import org.apache.commons.dbcp.BasicDataSource;
import org.dom4j.Document;
import org.dom4j.Element;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XMLConfigBuilder {
    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    public Configuration parseConfiguration(Element rootElement) {
        parseEnvironments(rootElement.element("environments"));

        parseMappers(rootElement.element("mappers"));

        return configuration;
    }

    private void parseMappers(Element mappers) {
        List<Element> mapperElements = mappers.elements();
        for (Element mapperElement : mapperElements) {
            String resource = mapperElement.attributeValue("resource");
            InputStream is = Resources.getResourceAsStream(resource);
            Document document = DocumentUtils.createDocument(is);

            XMLMapperBuilder builder = new XMLMapperBuilder(configuration);

            builder.parseMapper(document.getRootElement());
        }
    }

    private void parseEnvironments(Element environments) {
        String defaultEnvId = environments.attributeValue("default");
        if(defaultEnvId == null || defaultEnvId.equals("")){
            return ;
        }
        List<Element> elements = environments.elements();
        for (Element envElement : elements) {
            String envId = envElement.attributeValue("id");
            if(defaultEnvId.equals(envId)){
                parseDataSource(envElement.element("datasource"));
            }
        }
    }

    private void parseDataSource(Element datasource) {
        String type = datasource.attributeValue("type");
        if(type == null || type.equals("")){
            return ;
        }
        Properties properties = parseProperty(datasource);
        if (type.equals("DBCP")){
            BasicDataSource dataSource = new BasicDataSource();
            dataSource.setDriverClassName(properties.getProperty("driverClassName"));
            dataSource.setUrl(properties.getProperty("url"));
            dataSource.setUsername(properties.getProperty("username"));
            dataSource.setPassword(properties.getProperty("password"));

            configuration.setDataSource(dataSource);
        }
    }

    private Properties parseProperty(Element datasource) {
        List<Element> propertyElements = datasource.elements("property");

        Properties properties = new Properties();
        for (Element propertyElement : propertyElements) {
            String name = propertyElement.attributeValue("name");
            String value = propertyElement.attributeValue("value");

            properties.setProperty(name,value);
        }
        return properties;
    }

}
